import unittest


from selenium import webdriver
from selenium.webdriver.edge.service import Service as EdgeService
from selenium.webdriver.edge.options import Options as EdgeOptions
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from login import Lt


class TestLogin(unittest.TestCase):

    @classmethod
    def setUpClass(cls):
        """在所有测试开始前运行一次，用于初始化资源"""
        service = EdgeService(executable_path='D:\浏览器驱动\edge驱动\msedgedriver.exe')
        edge_options = EdgeOptions()
        cls.driver = webdriver.Edge(service=service, options=edge_options)
        cls.driver.maximize_window()  # 可选：最大化窗口

    def setUp(self):
        """每个测试方法之前都会调用，可以用来重置或初始化状态"""
        self.driver.get('http://www.codelover.club')  # 请替换为实际网址
        self.login_test = Lt(self.driver)

    def test_successful_login(self):
        """测试成功登录"""
        self.login_test.log(username="23003025", password="123456")

        # 验证登录成功的标志（例如欢迎信息）
        welcome_message = WebDriverWait(self.driver, 2).until(
            EC.presence_of_element_located((By.XPATH, '/html/body/div[2]/span/div/div/div/span[contains(text(), "登录成功")]'))
        )
        self.assertIsNotNone(welcome_message, "登陆成功")

    def test_failed_login(self):
        """测试失败登录（使用错误的凭据）"""
        self.login_test.log(username="23003025", password="1")

        # 验证登录失败的标志（例如错误信息）
        error_message = WebDriverWait(self.driver, 2).until(
            EC.presence_of_element_located((By.XPATH, '/html/body/div[2]/span/div/div/div/span[contains(text(), "用户名或密码错误")]'))
        )
        self.assertIsNotNone(error_message, "应显示错误信息但未显示")

    @classmethod
    def tearDownClass(cls):
        """所有测试结束后运行一次，关闭浏览器"""
        if cls.driver:
            cls.driver.quit()


if __name__ == '__main__':
    unittest.main()